class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        if len(nums) < 4:
            return []
        re=[]
        nums.sort()
        length = len(nums)
        for i in range(length-3):
            if i>0 and nums[i] == nums[i-1]:
                continue
            if nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target:
                break
            if nums[i] + nums[length - 3] + nums[length - 2] + nums[length - 1] < target:
                continue
            for j in range(i+1,length-2):
                x=nums[i]+nums[j]
                l=j+1
                r=len(nums)-1
                if j>i+1 and nums[j] == nums[j-1]:
                    continue
                if nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target:
                    break
                if nums[i] + nums[j] + nums[length - 2] + nums[length - 1] < target:
                    continue
                while l<r:
                    if x+nums[l]+nums[r]==target:
                        re.append([nums[i],nums[j],nums[l],nums[r]])
                        while l < len(nums)-1 and  nums[l] == nums[l+1]:
                            l+=1
                        while r>l+1 and  nums[r] == nums[r-1]:
                            r-=1
                        
                    if x+nums[l]+nums[r]>target:
                        r-=1
                    else:
                        l+=1
        return re